package com.tma.demo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class GoodActivity extends Activity implements OnClickListener {

    private static final String TAG = "GoodActivity";
    private TextView mTaskProgressTextView;
    private Button mDoLongTaskButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good);

        mTaskProgressTextView = (TextView) findViewById(R.id.tv_task_progress);
        mDoLongTaskButton = (Button) findViewById(R.id.btn_do_long_task);
        mDoLongTaskButton.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_good, menu);
        return true;
    }

    public void onClick(View v) {
        handleButtonClicked();
    }

    private void handleButtonClicked() {
        MyHandler handler = new MyHandler(this);
        handler.doDeferWork();
    }

    public void printWorkProgress(int percent, int total) {
        String s = getString(R.string.tv_task_progress) + ": " + percent + "/" + total;
        mTaskProgressTextView.setText(s);
    }

    private static class MyHandler extends Handler {
        private int mCount = 0;
        private GoodActivity mActivity;

        public MyHandler(GoodActivity activity) {
            mActivity = activity;
        }

        @Override
        public void handleMessage(Message msg) {
            // We use handler to perform an action 5 times at 1 second interval
            // So that the main thread can get back to its queue
            // And we can avoid ANR message
            //
            // It is important to note that the code here is still executed on the main thread!!!
            Log.i(TAG, "Receive: " + msg);
            mCount++;

            if (mCount > 5) {
                return;
            }
            reportProgress();
            sendMessage(1);
        }

        public void doDeferWork() {
            mCount = 0;
            sendMessage(1);
        }

        private void sendMessage(long interval) {
            Message m = Message.obtain();
            prepareMessage(m);
            sendMessageDelayed(m, interval * 1000);
        }

        private void prepareMessage(Message m) {
            // we can put extra bundle to message
            //Bundle b = new Bundle();
            //b.putString("key", "value");
            //m.setData(b);
        }

        private void reportProgress() {
            mActivity.printWorkProgress(mCount, 5);
        }
    }
}
